package com.atguigu.tingshu.order.pattern;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author NJG
 * @version 1.0
 * @date 2025/8/5 15:53
 * @description
 */
public abstract class AbstractTradeStrategy implements TradeStrategy{

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成流水号,进行封装
     * @param orderInfoVo
     * @param userId
     */
    public void generateTradeNo(OrderInfoVo orderInfoVo, Long userId){
        //6.2 封装流水号
        //设置流水号的key
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //生成流水号  采用UUID作为流水号的值
        String tradeNo = IdUtil.randomUUID();
        //将流水号保存到redis中，设置过期时间
        redisTemplate.opsForValue().set(tradeKey, tradeNo, RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
        //封装流水号
        orderInfoVo.setTradeNo(tradeNo);
    }

    public void generateSign(OrderInfoVo orderInfoVo, Long userId){
       //6.3封装时间戳
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        //签名机制，时间戳+签名值，防止订单结算页数据被篡改
        //将订单VO转为Map对象，由于无法确定支付方式，固将VO中payWay为空属性排除掉
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);

    }
}
